﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Configuration;
using AjaxControlToolkit;
using System.IO;
using System.Net;
using Newtonsoft.Json;

using CE.HotelEan;
using HotelWS;
using CE.Expedia;
using CE.TravelInsurance;
using CE.Global;
using CE.Database;
using CE.User;

public partial class travel_hotels_results : System.Web.UI.Page
{
    private string _apikey = "98pndgasdzzxpugjzqpxw6za";
    private int _minorrev = 13;
    private Int64 _cid = 381988;

    //travel insurance
    private string outbounddate = "";
    private string inbounddate = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillChildAge();

            if (Session["hotelsearchid"] != null)
            {
                if (Session["hotelsearchid"].ToString() != "")
                {
                    HotelSearch(Convert.ToInt64(Session["hotelsearchid"].ToString()));
                    GetTravelInsurance();

                }

            }
            else
            {
                Response.Redirect("hotels-search.aspx");
            }

        }
    }

    private void GoSearch()
    {
        if (Session["hotelsearchid"] != null)
        {
            if (Session["hotelsearchid"].ToString() != "")
            {
                SaveSearchDetails();
                HotelSearch(Convert.ToInt64(Session["hotelsearchid"].ToString()));
                GetTravelInsurance();

            }
        }
        else
        {
            Response.Redirect("hotels-search.aspx");
        }
    }

    private void HotelSearch(Int64 hotelsearchid)
    {
        ExpediaHotelDB expdb = new ExpediaHotelDB();
        DataTable dtsearch = new DataTable();

        dtsearch = expdb.GetHotelSearchDetails(hotelsearchid);

        if (dtsearch.Rows.Count > 0)
        {
            string locationsearch = "";

            if (dtsearch.Rows[0]["StateProvinceCode"].ToString() != "")
            {
                locationsearch = dtsearch.Rows[0]["City"].ToString() +
                    ", " + GetCountryNameOfExpediaCountry(dtsearch.Rows[0]["CountryCode"].ToString()) +
                    ", " + dtsearch.Rows[0]["StateProvinceCode"].ToString() +
                    ", " + dtsearch.Rows[0]["CountryCode"].ToString();
            }
            else
            {
                locationsearch = dtsearch.Rows[0]["City"].ToString() +
                    ", " + GetCountryNameOfExpediaCountry(dtsearch.Rows[0]["CountryCode"].ToString()) +
                    ", " + dtsearch.Rows[0]["CountryCode"].ToString();
            }


            inputCountryCode.Value = dtsearch.Rows[0]["CountryCode"].ToString();
            lblSearchText.Text = locationsearch;
            txtsearchbox.Text = locationsearch;

            HotelServicesImplService hws = new HotelServicesImplService();
            //hws.getGeoLocation();
            HotelListRequest hlist = new HotelListRequest();

            //hlist.hotelIdList = 
            hlist.apiKey = _apikey;
            hlist.cid = _cid;
            hlist.minorRev = _minorrev;
            hlist.minorRevSpecified = true;
            hlist.customerIpAddress = Request.UserHostAddress;
            hlist.customerUserAgent = Request.Browser.ToString();

            if (inputCustomerSessionId.Value.Trim() != "")
            {
                hlist.customerSessionId = inputCustomerSessionId.Value;
            }

            outbounddate = CE.Global.General.GetUTCDateTime().AddDays(1).ToString("dd/MM/yyyy");
            inbounddate = CE.Global.General.GetUTCDateTime().AddDays(2).ToString("dd/MM/yyyy");

            if (dtsearch.Rows[0]["arrivalDate"].ToString() != "1/1/1900 12:00:00 AM")
            {
                inputCheckinDate.Value = Convert.ToDateTime(dtsearch.Rows[0]["arrivalDate"].ToString()).ToString("dd/MM/yyyy");
                inputCheckoutDate.Value = Convert.ToDateTime(dtsearch.Rows[0]["departureDate"].ToString()).ToString("dd/MM/yyyy");

                inbounddate = inputCheckinDate.Value;
                outbounddate = inputCheckoutDate.Value;


            }
            else
            {
                inputCheckinDate.Value = "dd/mm/yyyy";
                inputCheckoutDate.Value = "dd/mm/yyyy";
            }


            if (inputCheckinDate.Value != "dd/mm/yyyy" && inputCheckinDate.Value != "")
            {
                string checkin = inputCheckinDate.Value; // Request.Form["from"].ToString().Trim();
                string checkto = inputCheckoutDate.Value; // Request.Form["to"].ToString().Trim();

                string[] checkinformatted = checkin.Split('/');
                string checkindate = checkinformatted[1] + "-" + checkinformatted[0] + "-" + checkinformatted[2];

                string[] checkoutformatted = checkto.Split('/');
                string checkoutdate = checkoutformatted[1] + "-" + checkoutformatted[0] + "-" + checkoutformatted[2];

                hlist.arrivalDate = checkindate;
                hlist.departureDate = checkoutdate;

            }

            DataTable dtRoom = new DataTable();
            ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();

            string _strRoomXml = "";

            dtRoom = exproomdb.GetRoomDetails(hotelsearchid);

            if (dtRoom.Rows.Count > 0)
            {
                int iRoomCount = Convert.ToInt32(dtRoom.Rows.Count.ToString());
                ddlRooms.SelectedValue = dtRoom.Rows.Count.ToString();

                int iTotalAdults = 0;
                int iTotalChild = 0;

                HotelWS.Room[] noofroom = new HotelWS.Room[iRoomCount];
                for (int i = 0; i < iRoomCount; i++)
                {

                    if (i == 0) //Room 1
                    {
                        ddlAdultsRoom1.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom1.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";


                        if (ddlChildrenRoom1.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom1Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom1Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom1Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom1Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";
                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 1) //Room 2
                    {
                        ddlAdultsRoom2.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom2.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom2.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom2Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom2Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom2Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom2Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 2) //Room 3
                    {
                        ddlAdultsRoom3.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom3.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom3.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom3Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom3Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom3Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom3Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 3) //Room 4
                    {
                        ddlAdultsRoom4.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom4.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom4.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom4Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom4Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom4Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom4Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 4) //Room 5
                    {
                        ddlAdultsRoom5.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom5.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom5.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom5Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom5Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom5Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom5Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 5) //Room 6
                    {
                        ddlAdultsRoom6.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom6.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom6.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom6Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom6Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom6Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom6Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 6) //Room 7
                    {
                        ddlAdultsRoom7.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom7.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom7.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom7Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom7Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom7Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom7Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }
                    else if (i == 7) //Room 8
                    {
                        ddlAdultsRoom8.SelectedValue = dtRoom.Rows[i]["NoOfAdults"].ToString();
                        ddlChildrenRoom8.SelectedValue = dtRoom.Rows[i]["NoOfChildren"].ToString();

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";

                        if (ddlChildrenRoom8.SelectedValue != "0")
                        {
                            string[] childages = dtRoom.Rows[i]["info1"].ToString().Split(',');
                            ddlChildRoom8Child1Age.SelectedValue = childages[0].Trim();

                            if (childages.Length == 2)
                            {
                                ddlChildRoom8Child2Age.SelectedValue = childages[1].Trim();
                            }

                            if (childages.Length == 3)
                            {
                                ddlChildRoom8Child3Age.SelectedValue = childages[2].Trim();
                            }
                            if (childages.Length == 4)
                            {
                                ddlChildRoom8Child4Age.SelectedValue = childages[3].Trim();
                            }

                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";

                        }

                        _strRoomXml += "</Room>";
                    }

                    HotelWS.Room roomdtls = new HotelWS.Room();

                    roomdtls.numberOfAdults = int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString());
                    roomdtls.numberOfChildren = int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString());
                    roomdtls.numberOfChildrenSpecified = true;

                    noofroom[i] = roomdtls;

                    iTotalAdults = iTotalAdults + int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString());
                    iTotalChild = iTotalChild + int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString());
                }

                inputTotalAdults.Value = iTotalAdults.ToString();
                inputTotalChild.Value = iTotalChild.ToString();

                hlist.RoomGroup = noofroom;
                hlist.numberOfBedRooms = iRoomCount;
                hlist.numberOfBedRoomsSpecified = true;
            }

            hlist.destinationId = "";

            if (dtsearch.Rows[0]["info1"] != null)
            {
                if (dtsearch.Rows[0]["info1"].ToString() != "")
                {
                    inputDestinationID.Value = dtsearch.Rows[0]["info1"].ToString();
                    inputDestinationID2.Value = dtsearch.Rows[0]["info1"].ToString();
                    hlist.destinationId = dtsearch.Rows[0]["Info1"].ToString();
                }
            }


            //if (txtsearchbox.Text == "")
            //{

            //    hlist.city = dtsearch.Rows[0]["City"].ToString(); //"Seattle";
            //    hlist.stateProvinceCode = dtsearch.Rows[0]["StateProvinceCode"].ToString(); //"WA";
            //    hlist.countryCode = dtsearch.Rows[0]["CountryCode"].ToString(); //"US";
            //    hlist.destinationString = txtsearchbox.Text;
            //    hlist.destinationId = dtsearch.Rows[0]["Info1"].ToString();
            //    inputDestinationID.Value = dtsearch.Rows[0]["Info1"].ToString();
            //}
            //else
            //{
            //    string[] location = GetLocationByDestination(txtsearchbox.Text, ddlHotelNear.SelectedValue);
            //    inputDestinationID.Value = location[1];
            //    hlist.destinationId = location[1];
            //    txtsearchbox.Text = location[0];
            //    lblSearchText.Text = location[0];
            //}

            //hlist.destinationString = dtsearch.Rows[0]["City"].ToString();

            hlist.currencyCode = "SGD";
            hlist.supplierCacheTolerance = HotelWS.SupplierCacheTolerance.MED_ENHANCED;

            hlist.numberOfResultsSpecified = true;
            hlist.numberOfResults = 30;
            hlist.locale = LocaleType.en_US;

            //filters
            hlist.propertyName = txtHotelName.Text;

            int maxprice = 0;
            int minprice = 0;

            hlist.maxRateSpecified = false;
            hlist.minRateSpecified = false;

            if (rdoPricing.SelectedValue != "All")
            {
                if (rdoPricing.SelectedValue == "500")
                {
                    maxprice = 1500;
                    minprice = 500;
                }
                else if (rdoPricing.SelectedValue == "499")
                {
                    maxprice = 499;
                    minprice = 325;
                }
                else if (rdoPricing.SelectedValue == "324")
                {
                    maxprice = 324;
                    minprice = 200;
                }
                else if (rdoPricing.SelectedValue == "199")
                {
                    maxprice = 199;
                    minprice = 100;
                }
                else if (rdoPricing.SelectedValue == "99")
                {
                    maxprice = 99;
                    minprice = 0;
                }

                hlist.maxRate = maxprice;
                hlist.minRate = minprice;

                hlist.maxRateSpecified = true;
                hlist.minRateSpecified = true;
            }



            if (chkrating5.Checked == false && chkrating4.Checked == false && chkrating3.Checked == false
                && chkrating2.Checked == false && chkrating1.Checked == false)
            {
                hlist.minStarRatingSpecified = false;
                hlist.maxStarRatingSpecified = false;
            }
            else
            {
                hlist.minStarRatingSpecified = true;
                hlist.maxStarRatingSpecified = true;

                float maxrate = 0;
                float minrate = 0;

                if (chkrating5.Checked)
                {
                    maxrate = 5;
                    minrate = 5;
                }
                if (chkrating4.Checked)
                {
                    if (maxrate == 0)
                    {
                        maxrate = 4;
                    }

                    minrate = 4;
                }
                if (chkrating3.Checked)
                {
                    if (maxrate == 0)
                    {
                        maxrate = 3;
                    }

                    minrate = 3;
                }
                if (chkrating2.Checked)
                {
                    if (maxrate == 0)
                    {
                        maxrate = 4;
                    }

                    minrate = 2;
                }
                if (chkrating1.Checked)
                {
                    if (maxrate == 0)
                    {
                        maxrate = 4;
                    }

                    minrate = 1;
                }

                hlist.maxStarRating = maxrate;
                hlist.minStarRating = minrate;

            }

            hlist.sortSpecified = true;
            AlternatePropertyListRequest ts = new AlternatePropertyListRequest();

            string sortby = ddlSortBy.SelectedValue;

            if (sortby == "price-lowtohigh")
            {
                hlist.sort = SortType.PRICE;
            }
            else if (sortby == "price-hightolow")
            {
                hlist.sort = SortType.PRICE_REVERSE;
            }
            if (sortby == "star-lowtohigh")
            {
                hlist.sort = SortType.QUALITY_REVERSE;
            }
            else if (sortby == "star-hightolow")
            {
                hlist.sort = SortType.QUALITY;
            }
            else if (sortby == "hotelname")
            {
                hlist.sort = SortType.ALPHA;
            }
            else
            {
                hlist.sort = SortType.OVERALL_VALUE;
            }

            //if (chkswimmingpool.Checked || chkfitness.Checked || chkrestaurant.Checked || chkchildactivity.Checked || chkbreakfast.Checked
            //    || chkmeeting.Checked || chkpets.Checked || chkwheelchair.Checked || chkkitchen.Checked)
            //{
            //    Amenities hotelam = new Amenities();
            //    hotelam.businessCenter = true;

            //    //int[] findamenities = new int[] 
            //    //hlist.amenities = hotelam;
            //}
            // if (chkAmenities.Items.Count)


            bool filterAmenities = false;
            string selectedAmenity = "";

            for (int i = 0; i < chkAmenities.Items.Count; i++)
            {
                if (chkAmenities.Items[i].Selected)
                {
                    filterAmenities = true;

                    if (selectedAmenity == "")
                    {
                        selectedAmenity = chkAmenities.Items[i].Value;
                    }
                    else
                    {
                        selectedAmenity = chkAmenities.Items[i].Value + "," + selectedAmenity;
                    }
                }

            }


            if (filterAmenities)
            {
                string[] findamenities = selectedAmenity.Split(',');
                int[] iAmenities = new int[findamenities.Length];

                for (int a = 0; a < findamenities.Length; a++)
                {
                    iAmenities[a] = int.Parse(findamenities[a]);
                }

                hlist.amenities = iAmenities;

            }


            //reformat date
            hlist.arrivalDate = hlist.arrivalDate.Replace("-", "/");
            hlist.departureDate = hlist.departureDate.Replace("-", "/");

            string getData = "http://api.ean.com/ean-services/rs/hotel/v3/list?cid=" + _cid
                + "&minorRev=26&apiKey=" + _apikey
                + "&locale=" + hlist.locale
                + "&currencyCode=" + hlist.currencyCode
                + "&customerIpAddress=" + hlist.customerIpAddress
                + "&customerUserAgent=" + hlist.customerUserAgent
                + "&_type=xml&customerSessionId=" + hlist.customerSessionId
                + "&xml="
                + "<HotelListRequest><arrivalDate>" + hlist.arrivalDate +
                "</arrivalDate><departureDate>" + hlist.departureDate +
                "</departureDate><numberOfBedRooms>" + hlist.numberOfBedRooms + "</numberOfBedRooms><RoomGroup>" + _strRoomXml +
                "</RoomGroup><destinationId>" + hlist.destinationId +
                "</destinationId><numberOfResults>" + hlist.numberOfResults +
                "</numberOfResults><supplierCacheTolerance>" + hlist.supplierCacheTolerance.ToString() +
                "</supplierCacheTolerance><sort>" + hlist.sort.ToString() +
                "</sort> ";

            if(hlist.propertyName != "")
                getData += "<propertyName>" + hlist.propertyName + "</propertyName>";

            if (hlist.maxRateSpecified && hlist.minRateSpecified)
            {
                getData += "<minRate>" + hlist.minRate + "</minRate>";
                getData += "<maxRate>" + hlist.maxRate + "</maxRate>";
            }

            if (hlist.maxStarRatingSpecified && hlist.minStarRatingSpecified)
            {
                getData += "<minStarRating>" + hlist.minStarRating + "</minStarRating>";
                getData += "<maxStarRating>" + hlist.maxStarRating + "</maxStarRating>";
            }

            if (hlist.amenities != null)
                getData += "<amenities>" + selectedAmenity + "</amenities>";

            getData += "</HotelListRequest>";

            CXHotel hlistresult = new CXHotel();

            // Handle JsonConvert array bug
            string returnJson = "";
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(getXMLResult(getData));
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//ValueAdds"))
            {
                item.AppendChild(doc.CreateNode("element", "ValueAdd", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//HotelFees"))
            {
                item.AppendChild(doc.CreateNode("element", "HotelFee", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
            {
                item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//RoomGroup"))
            {
                item.AppendChild(doc.CreateNode("element", "Room", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
            {
                item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//HotelList"))
            {
                item.AppendChild(doc.CreateNode("element", "HotelSummary", ""));
            }
            returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

            returnJson = returnJson.Replace("@", "");
            returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
            returnJson = returnJson.Replace("ns2:", ""); 
            hlistresult = JsonConvert.DeserializeObject<CXHotel>(returnJson);

            //HotelWS.HotelListResponse hlistresult2 = new HotelWS.HotelListResponse();

            //hlistresult2 = hws.getList(hlist);

            if (hlistresult != null && hlistresult.HotelListResponse.EanWsError == null)
            {
                if (hlistresult.HotelListResponse.HotelList.activePropertyCount > 0)
                //if (hlistresult.HotelListResponse.HotelList.HotelSummary.Length > 0)
                {
                    //inputCacheKey.Value = hlistresult.cacheKey.ToString().Trim();
                    //inputCacheLocation.Value = hlistresult.cacheLocation.ToString().Trim();
                    inputCustomerSessionId.Value = hlistresult.HotelListResponse.customerSessionId.ToString().Trim();

                    BindData(hlistresult.HotelListResponse);

                    //int TotalHotels = hlistresult.HotelList.activePropertyCount; // hlistresult.LocationInfos.LocationInfo.Length;
                    lblMessage.Text = hlistresult.HotelListResponse.HotelList.activePropertyCount.ToString() + " hotels match your selection";
                    //lblMessage.Text = TotalHotels.ToString() + " hotels match your selection";

                    if (hlistresult.HotelListResponse.HotelList.HotelSummary != null)
                    {
                        if (hlistresult.HotelListResponse.HotelList.HotelSummary.Length < 30)
                        {
                            lblMessage.Text = hlistresult.HotelListResponse.HotelList.HotelSummary.Length.ToString() + " hotels match your selection";
                        }
                    }

                    if (gvResults.Rows.Count <= 0)
                    {
                        lblMessage.Text = "0 hotels match your selection";
                    }

                    //inputHotelCount.Value = TotalHotels.ToString();
                    //lblResultsCountTop.Text = "1-10 of " + TotalHotels.ToString();
                    //lblResultsCount.Text = "1-10 of " + TotalHotels.ToString();

                    //if (hlistresult.HotelList.activePropertyCount < 10)
                    //{
                    //    lblResultsCountTop.Text = "1-" + TotalHotels.ToString() + " of " + TotalHotels.ToString();
                    //    lblResultsCount.Text = "1-" + TotalHotels.ToString() + " of " + TotalHotels.ToString();
                    //}

                }
                else
                {
                    lblMessage.Text = "";
                }
            }
            else
            {
                lblMessage.Text = hlistresult.HotelListResponse.EanWsError.presentationMessage;

                gvResults.DataBind();
            }

        }
        else
        {
            Response.Redirect("hotels-search.aspx");
        }
    }

    private void HotelSearchPaging(string prevnext)
    {
        HotelServicesImplService hws = new HotelServicesImplService();
        //hws.getGeoLocation();
        HotelListRequest hlist = new HotelListRequest();

        //hlist.hotelIdList = 
        hlist.apiKey = _apikey;
        hlist.cid = _cid;
        hlist.minorRev = _minorrev;
        hlist.customerIpAddress = Request.UserHostAddress;
        hlist.customerUserAgent = Request.Browser.ToString();
        hlist.customerSessionId = inputCustomerSessionId.Value;
        hlist.currencyCode = "SGD";
        hlist.locale = LocaleType.en_US;

        if (prevnext == "next")
        {
            hlist.cacheKey = inputCacheKey.Value;
            hlist.cacheLocation = inputCacheLocation.Value;
        }
        else
        {
            hlist.cacheKey = inputCacheKeyPrevious.Value;
            hlist.cacheLocation = inputCacheLocationPrevious.Value;
        }


        HotelWS.HotelListResponse hlistresult = new HotelWS.HotelListResponse();
        hlistresult = hws.getList(hlist);

        if (hlistresult != null && hlistresult.EanWsError == null)
        {
            if (hlistresult.HotelList.activePropertyCount > 0)
            {
                if (prevnext == "next")
                {
                    inputCacheKeyPrevious.Value = inputCacheKey.Value;
                    inputCacheKey.Value = hlistresult.cacheKey.ToString().Trim();

                    inputCacheLocationPrevious.Value = inputCacheLocation.Value;
                    inputCacheLocation.Value = hlistresult.cacheLocation.ToString().Trim();
                }
                else
                {
                }


                inputCustomerSessionId.Value = hlistresult.customerSessionId.ToString().Trim();

                //BindData(hlistresult);

                if (hlistresult.moreResultsAvailable)
                {
                    lnkbtnNextPage.Enabled = true;
                }
                else
                {
                    lnkbtnNextPage.Enabled = false;
                }

                //inputCurrentHotelCount.Value = hlistresult.HotelList.activePropertyCount.ToString();

                //int TotalCount = int.Parse(inputHotelCount.Value);
                //int CurrentTotal = int.Parse(inputCurrentHotelCount.Value);

                //int ToCount = (TotalCount - CurrentTotal) + 1;
                //int FromCount = ToCount - 9;

                //lblResultsCountTop.Text = FromCount.ToString() + "-" + ToCount.ToString() + " of " + TotalCount.ToString();
                //lblResultsCount.Text = FromCount.ToString() + "-" + ToCount.ToString() + " of " + TotalCount.ToString();

            }
        }
        else if (hlistresult.EanWsError.presentationMessage.Trim() == "No Results Available")
        {
            lnkbtnNextPage.Enabled = false;
        }
        else
        {
            lblMessage.Text = hlistresult.EanWsError.presentationMessage;
        }


    }

    private Int64 SaveSearchDetails()
    {
        Int64 _hotelsearchid = 0;

        string checkindate = inputCheckinDate.Value.Trim();
        string checkoutdate = inputCheckoutDate.Value.Trim();
        string arrivaldate = "";
        string departuredate = "";

        if (inputCheckinDate.Value != "dd/mm/yyyy")
        {
            string[] arrivaldateformatted = checkindate.Split('/');
            arrivaldate = arrivaldateformatted[2] + "-" + arrivaldateformatted[1] + "-" + arrivaldateformatted[0];

            string[] departuredateformatted = checkoutdate.Split('/');
            departuredate = departuredateformatted[2] + "-" + departuredateformatted[1] + "-" + departuredateformatted[0];
        }
        else
        {
            arrivaldate = "1900-01-01 00:00:00.000";
            departuredate = "1900-01-01 00:00:00.000";
        }

        string _city = "";
        string _statecode = "";
        string _countryname = "";
        string _countrycode = "";
        string hotelsearchtext = "";

        if (inputDestinationID.Value != inputDestinationID2.Value && inputDestinationID2.Value != "")
        {
            lblSearchText.Text = txtsearchbox.Text;
            inputDestinationID.Value = inputDestinationID2.Value;
        }
        else
        {

            string[] location = GetLocationByDestination(txtsearchbox.Text, ddlHotelNear.SelectedValue);
            inputDestinationID.Value = location[1];
            txtsearchbox.Text = location[0];
            lblSearchText.Text = location[0];
            inputCountryCode.Value = location[2];

        }

        hotelsearchtext = txtsearchbox.Text;

        string[] getlocs = hotelsearchtext.Split(',');
        _city = getlocs[0];
        _statecode = "";
        _countryname = "";
        _countrycode = "";

        if (getlocs.Length == 3)
        {
            _countryname = getlocs[1];
            _countrycode = getlocs[2];
        }
        else if (getlocs.Length == 4)
        {
            _statecode = getlocs[1];
            _countryname = getlocs[2];
            _countrycode = getlocs[3];
        }



        ExpediaHotelInfo expinfo = new ExpediaHotelInfo();

        expinfo.City = _city.Trim(); // "Seattle";
        expinfo.StateProvinceCode = _statecode.Trim(); // "WA";
        expinfo.CountryCode = _countrycode.Trim(); // "US";
        expinfo.ArrivalDate = Convert.ToDateTime(arrivaldate);
        expinfo.DepartureDate = Convert.ToDateTime(departuredate);
        expinfo.NoOfRooms = Convert.ToInt32(ddlRooms.SelectedValue.ToString());
        expinfo.StarRating = 0;
        expinfo.HotelChain = "";
        expinfo.Amenities = "";
        expinfo.Info1 = inputDestinationID.Value.Trim();

        ExpediaHotelDB expdb = new ExpediaHotelDB();
        _hotelsearchid = expdb.Insert(expinfo);

        if (_hotelsearchid > 0)
        {
            Session["hotelsearchid"] = _hotelsearchid.ToString();

            int iRoomCount = Convert.ToInt32(ddlRooms.SelectedValue.ToString());

            for (int i = 0; i < iRoomCount; i++)
            {
                ExpediaHotelRoomInfo exproominfo = new ExpediaHotelRoomInfo();
                exproominfo.HotelSearchID = _hotelsearchid;
                string childage = "";

                if (i == 0) //Room 1
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom1.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom1.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom1Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom1Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom1Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom1Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 1)  //Room 2
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom2.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom2.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom2Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom2Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom2Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom2Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 2) //Room 3
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom3.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom3.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom3Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom3Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom3Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom3Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 3) //Room 4
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom4.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom4.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom4Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom4Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom4Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom4Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 4) //Room 5
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom5.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom5.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom5Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom5Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom5Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom5Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 5) //Room 6
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom6.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom6.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom6Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom6Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom6Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom6Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 6) //Room 7
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom7.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom7.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom7Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom7Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom7Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom7Child4Age.SelectedValue;
                            }
                        }
                    }
                }
                else if (i == 7) //Room 8
                {
                    exproominfo.NoOfAdults = Convert.ToInt32(ddlAdultsRoom8.SelectedValue);
                    exproominfo.NoOfChildren = Convert.ToInt32(ddlChildrenRoom8.SelectedValue);

                    if (exproominfo.NoOfChildren > 0)
                    {
                        for (int c = 0; c < exproominfo.NoOfChildren; c++)
                        {
                            if (c == 0)
                            {
                                childage = ddlChildRoom8Child1Age.SelectedValue;
                            }
                            if (c == 1)
                            {
                                childage = childage + ", " + ddlChildRoom8Child2Age.SelectedValue;
                            }
                            if (c == 2)
                            {
                                childage = childage + ", " + ddlChildRoom8Child3Age.SelectedValue;
                            }
                            if (c == 3)
                            {
                                childage = childage + ", " + ddlChildRoom8Child4Age.SelectedValue;
                            }
                        }
                    }
                }

                exproominfo.Info1 = childage;

                ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();
                exproomdb.Insert(exproominfo);

            }

        }

        return _hotelsearchid;
    }

    private string[] GetLocationByDestination(string destination, string searchtype)
    {
        string[] location = new string[3];
        HotelServicesImplService hws = new HotelServicesImplService();

        LocationInfoRequest locinforeq = new LocationInfoRequest();
        locinforeq.apiKey = _apikey;
        locinforeq.cid = _cid;
        locinforeq.minorRev = _minorrev;
        locinforeq.customerIpAddress = Request.UserHostAddress;
        locinforeq.customerUserAgent = Request.Browser.ToString();
        locinforeq.customerSessionId = "";
        locinforeq.destinationString = destination;
        locinforeq.localeSpecified = true;
        locinforeq.ignoreSearchWeight = true;
        locinforeq.typeSpecified = true;

        if (searchtype == "city")
        {
            locinforeq.type = LocationInfoType.Item1;
        }
        else if (searchtype == "airport")
        {
            locinforeq.type = LocationInfoType.Item4;
        }
        else if (searchtype == "landmark")
        {
            locinforeq.type = LocationInfoType.Item2;
        }

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/geoSearch?cid=" + locinforeq.cid
                + "&minorRev=26&apiKey=" + locinforeq.apiKey
                + "&customerIpAddress=" + locinforeq.customerIpAddress
                + "&customerUserAgent=" + locinforeq.customerUserAgent
                + "&_type=xml&customerSessionId=" + locinforeq.customerSessionId
                + "&xml="
                + "<LocationInfoRequest><type>" + locinforeq.type +
                "</type><destinationString>" + locinforeq.destinationString +
                "</destinationString><ignoreSearchWeight>" + locinforeq.ignoreSearchWeight +
                "</ignoreSearchWeight>";

        getData += "</LocationInfoRequest>";

        CXLocation locinforesp = new CXLocation();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//LocationInfos"))
        {
            item.AppendChild(doc.CreateNode("element", "LocationInfo", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        locinforesp = JsonConvert.DeserializeObject<CXLocation>(returnJson);

        //HotelWS.LocationInfoResponse locinforesp = new HotelWS.LocationInfoResponse();
        //locinforesp = hws.getGeoLocation(locinforeq);

        if (locinforesp != null & locinforesp.LocationInfoResponse.EanWsError == null)
        {
            if (locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].stateProvinceCode != null && locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].stateProvinceCode != "")
            {
                location[0] = locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].city + ", " + locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].stateProvinceCode
                    + ", " + locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].countryName + ", " + locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].countryCode;
            }
            else
            {
                location[0] = locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].city + ", " + locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].countryName + ", " + locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].countryCode;
            }

            location[1] = locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].destinationId;
            location[2] = locinforesp.LocationInfoResponse.LocationInfos.LocationInfo[0].countryCode;

        }
        else
        {
            location[0] = locinforesp.LocationInfoResponse.EanWsError.presentationMessage;
            location[1] = "";
            location[2] = "";
        }

        return location;
    }

    private void FillChildAge()
    {
        for (int i = 17; i >= 0; i--)
        {
            if (i == 0)
            {
                ddlChildRoom1Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom1Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom1Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom1Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom2Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom2Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom2Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom2Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom3Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom3Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom3Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom3Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom4Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom4Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom4Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom4Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom5Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom5Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom5Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom5Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom6Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom6Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom6Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom6Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom7Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom7Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom7Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom7Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));

                ddlChildRoom8Child1Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom8Child2Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom8Child3Age.Items.Insert(0, new ListItem("<1", i.ToString()));
                ddlChildRoom8Child4Age.Items.Insert(0, new ListItem("<1", i.ToString()));
            }
            else
            {
                ddlChildRoom1Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom1Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom1Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom1Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom2Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom2Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom2Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom2Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom3Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom3Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom3Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom3Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom4Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom4Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom4Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom4Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom5Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom5Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom5Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom5Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom6Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom6Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom6Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom6Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom7Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom7Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom7Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom7Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));

                ddlChildRoom8Child1Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom8Child2Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom8Child3Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));
                ddlChildRoom8Child4Age.Items.Insert(0, new ListItem(i.ToString(), i.ToString()));


            }
        }
        //ddlChildRoom1Child1Age.Items.Insert(0, new ListItem("?", "-1"));
    }

    private void BindData(CE.HotelEan.HotelListResponse hlistresult)
    {
        DataTable dtHotelList = new DataTable();

        DataColumn col1 = new DataColumn("hotelId");
        DataColumn col2 = new DataColumn("name");
        DataColumn col3 = new DataColumn("address1");
        DataColumn col4 = new DataColumn("city");
        DataColumn col5 = new DataColumn("stateProvinceCode");
        DataColumn col6 = new DataColumn("postalCode");
        DataColumn col7 = new DataColumn("countryCode");
        DataColumn col8 = new DataColumn("airportCode");
        DataColumn col9 = new DataColumn("propertyCategory");
        DataColumn col10 = new DataColumn("hotelRating");
        DataColumn col11 = new DataColumn("confidenceRating");
        DataColumn col12 = new DataColumn("amenityMask");
        DataColumn col13 = new DataColumn("tripAdvisorRating");
        DataColumn col14 = new DataColumn("tripAdvisorReviewCount");
        DataColumn col15 = new DataColumn("tripAdvisorRatingUrl");
        DataColumn col16 = new DataColumn("locationDescription");
        DataColumn col17 = new DataColumn("shortDescription");
        DataColumn col18 = new DataColumn("highRate");
        DataColumn col19 = new DataColumn("lowRate");
        DataColumn col20 = new DataColumn("rateCurrencyCode");
        DataColumn col21 = new DataColumn("latitude");
        DataColumn col22 = new DataColumn("longitude");
        DataColumn col23 = new DataColumn("proximityDistance");
        DataColumn col24 = new DataColumn("proximityUnit");
        DataColumn col25 = new DataColumn("hotelInDestination");
        DataColumn col26 = new DataColumn("thumbNailUrl");
        DataColumn col27 = new DataColumn("deepLink");

        DataColumn col28 = new DataColumn("promo");
        DataColumn col29 = new DataColumn("promoDescription");
        DataColumn col30 = new DataColumn("averageBaseRate");
        DataColumn col31 = new DataColumn("averageRate");
        DataColumn col32 = new DataColumn("supplierType");

        col31.DataType = System.Type.GetType("System.Decimal");

        dtHotelList.Columns.Add(col1);
        dtHotelList.Columns.Add(col2);
        dtHotelList.Columns.Add(col3);
        dtHotelList.Columns.Add(col4);
        dtHotelList.Columns.Add(col5);
        dtHotelList.Columns.Add(col6);
        dtHotelList.Columns.Add(col7);
        dtHotelList.Columns.Add(col8);
        dtHotelList.Columns.Add(col9);
        dtHotelList.Columns.Add(col10);
        dtHotelList.Columns.Add(col11);
        dtHotelList.Columns.Add(col12);
        dtHotelList.Columns.Add(col13);
        dtHotelList.Columns.Add(col14);
        dtHotelList.Columns.Add(col15);
        dtHotelList.Columns.Add(col16);
        dtHotelList.Columns.Add(col17);
        dtHotelList.Columns.Add(col18);
        dtHotelList.Columns.Add(col19);
        dtHotelList.Columns.Add(col20);
        dtHotelList.Columns.Add(col21);
        dtHotelList.Columns.Add(col22);
        dtHotelList.Columns.Add(col23);
        dtHotelList.Columns.Add(col24);
        dtHotelList.Columns.Add(col25);
        dtHotelList.Columns.Add(col26);
        dtHotelList.Columns.Add(col27);

        dtHotelList.Columns.Add(col28);
        dtHotelList.Columns.Add(col29);
        dtHotelList.Columns.Add(col30);
        dtHotelList.Columns.Add(col31);
        dtHotelList.Columns.Add(col32);

        if (hlistresult.HotelList.HotelSummary != null)
        {
            foreach (CE.HotelEan.HotelSummary hotelrow in hlistresult.HotelList.HotelSummary)
            {
                if (hotelrow.supplierType == CE.HotelEan.SupplierType.E) //display only Merchants hotel
                {
                    DataRow row = dtHotelList.NewRow();
                    row["hotelId"] = hotelrow.hotelId;
                    row["name"] = hotelrow.name;
                    row["address1"] = hotelrow.address1;
                    row["city"] = hotelrow.city;
                    row["stateProvinceCode"] = hotelrow.stateProvinceCode;
                    row["postalCode"] = hotelrow.postalCode;
                    row["countryCode"] = hotelrow.countryCode;
                    row["airportCode"] = hotelrow.airportCode;
                    row["propertyCategory"] = hotelrow.propertyCategory;
                    row["hotelRating"] = hotelrow.hotelRating;
                    row["confidenceRating"] = hotelrow.confidenceRating;
                    row["amenityMask"] = hotelrow.amenityMask;
                    row["tripAdvisorRating"] = hotelrow.tripAdvisorRating;
                    row["tripAdvisorReviewCount"] = hotelrow.tripAdvisorReviewCount;
                    row["tripAdvisorRatingUrl"] = hotelrow.tripAdvisorRatingUrl;
                    row["locationDescription"] = hotelrow.locationDescription;
                    row["shortDescription"] = hotelrow.shortDescription;
                    row["highRate"] = hotelrow.highRate;
                    row["lowRate"] = hotelrow.lowRate;
                    row["rateCurrencyCode"] = hotelrow.rateCurrencyCode;
                    row["latitude"] = hotelrow.latitude;
                    row["longitude"] = hotelrow.longitude;
                    row["proximityDistance"] = hotelrow.proximityDistance;
                    row["proximityUnit"] = hotelrow.proximityUnit;
                    row["hotelInDestination"] = hotelrow.hotelInDestination;
                    row["thumbNailUrl"] = hotelrow.thumbNailUrl;
                    row["deepLink"] = hotelrow.deepLink;

                    row["supplierType"] = hotelrow.supplierType.ToString();

                    row["promo"] = "";
                    row["promoDescription"] = "";
                    row["averageBaseRate"] = "";
                    row["averageRate"] = "0";

                    if (hotelrow.RoomRateDetailsList != null)
                    {
                        if (hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos != null)
                        {
                            row["promo"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].promo;

                            if (hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                            {
                                row["promoDescription"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ChargeableRateInfo.promoDescription;
                                row["averageBaseRate"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ChargeableRateInfo.averageBaseRate.ToString();
                                row["averageRate"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ChargeableRateInfo.averageRate.ToString();
                            }
                            else
                            {
                                if (hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ConvertedRateInfo != null)
                                {
                                    row["promoDescription"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ConvertedRateInfo.promoDescription;
                                    row["averageBaseRate"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ConvertedRateInfo.averageBaseRate.ToString();
                                    row["averageRate"] = hotelrow.RoomRateDetailsList.RoomRateDetails.RateInfos.RateInfo[0].ConvertedRateInfo.averageRate.ToString();
                                }

                            }
                        }

                    }


                    dtHotelList.Rows.Add(row);
                }


            }

        }

        //dtHotelList = (DataTable)hlistresult.HotelList.HotelSummary;

        //price sorting - api is displaying the wrong sort order
        if (ddlSortBy.SelectedValue == "price-lowtohigh")
        {
            dtHotelList.DefaultView.Sort = "averageRate asc";
        }
        else if (ddlSortBy.SelectedValue == "price-hightolow")
        {
            dtHotelList.DefaultView.Sort = "averageRate desc";
        }

        dtHotelList.AcceptChanges();

        gvResults.DataSource = dtHotelList;
        gvResults.DataBind();

    }

    protected void gvResults_RowDatabound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Image imgHotelLogo = new Image();
            imgHotelLogo = (Image)e.Row.FindControl("imgHotelLogo");

            if (DataBinder.Eval(e.Row.DataItem, "thumbnailurl").ToString() != "")
            {
                imgHotelLogo.ImageUrl = "http://images.travelnow.com//" + DataBinder.Eval(e.Row.DataItem, "thumbnailurl").ToString();
            }

            Button btnRatings = new Button();
            btnRatings = (Button)e.Row.FindControl("btnRatings");

            string _hotelrating = DataBinder.Eval(e.Row.DataItem, "hotelRating").ToString();

            if (_hotelrating == "0")
            { btnRatings.CssClass = "rating-0"; }
            else if (_hotelrating == "1")
            { btnRatings.CssClass = "rating-1"; }
            else if (_hotelrating == "1.5")
            { btnRatings.CssClass = "rating-15"; }
            else if (_hotelrating == "2")
            { btnRatings.CssClass = "rating-2"; }
            else if (_hotelrating == "2.5")
            { btnRatings.CssClass = "rating-25"; }
            else if (_hotelrating == "3")
            { btnRatings.CssClass = "rating-3"; }
            else if (_hotelrating == "3.5")
            { btnRatings.CssClass = "rating-35"; }
            else if (_hotelrating == "4")
            { btnRatings.CssClass = "rating-4"; }
            else if (_hotelrating == "4.5")
            { btnRatings.CssClass = "rating-45"; }
            else if (_hotelrating == "5")
            { btnRatings.CssClass = "rating-5"; }

            Label lblCurrency = new Label();
            lblCurrency = (Label)e.Row.FindControl("lblCurrency");
            lblCurrency.Text = DataBinder.Eval(e.Row.DataItem, "rateCurrencyCode").ToString();

            Label lblPrice = new Label();
            lblPrice = (Label)e.Row.FindControl("lblPrice");

            int avgrate = 0;
            int avgbaserate = 0;
            if (DataBinder.Eval(e.Row.DataItem, "averagebaserate") != null)
            {
                if (DataBinder.Eval(e.Row.DataItem, "averagebaserate").ToString() != "")
                {
                    avgbaserate = (int)(Math.Round(float.Parse(DataBinder.Eval(e.Row.DataItem, "averagebaserate").ToString())));
                }
            }

            lblPrice.Text = avgbaserate.ToString();

            if (DataBinder.Eval(e.Row.DataItem, "supplierType").ToString() != "E")
            {
                lblCurrency.Text = "";
                lblPrice.Text = "check rates";
            }

            if (DataBinder.Eval(e.Row.DataItem, "promo").ToString() != "" & DataBinder.Eval(e.Row.DataItem, "promo").ToString() == "True")
            {
                avgrate = (int)(Math.Round(float.Parse(DataBinder.Eval(e.Row.DataItem, "averagerate").ToString())));

                lblPrice.Text = "<s>" + avgbaserate.ToString() + "</s>";

                Label lblCurrency2 = new Label();
                lblCurrency2 = (Label)e.Row.FindControl("lblCurrency2");
                lblCurrency2.Text = DataBinder.Eval(e.Row.DataItem, "rateCurrencyCode").ToString();

                Label lblPromoPrice = new Label();
                lblPromoPrice = (Label)e.Row.FindControl("lblPromoPrice");
                lblPromoPrice.Text = avgrate.ToString();

                Label lblPromoDesc = new Label();
                lblPromoDesc = (Label)e.Row.FindControl("lblPromoDesc");
                lblPromoDesc.Text = "SPECIAL PROMO! " + DataBinder.Eval(e.Row.DataItem, "promoDescription").ToString();
            }

            if (DataBinder.Eval(e.Row.DataItem, "supplierType").ToString() != "E")
            {
                Label lblPromoDesc = new Label();
                lblPromoDesc = (Label)e.Row.FindControl("lblPromoDesc");
                lblPromoDesc.Text = "ONLINE BOOKING ONLY";
            }

            HyperLink hlnkMoreDetails = new HyperLink();
            hlnkMoreDetails = (HyperLink)e.Row.FindControl("hlnkMoreDetails");
            hlnkMoreDetails.NavigateUrl = "details.aspx?hid=" + DataBinder.Eval(e.Row.DataItem, "hotelid").ToString();

        }
    }

    protected void gvResults_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvResults.Rows.Count > 0)
        {
            string hotelid = gvResults.SelectedDataKey.Value.ToString();

            Response.Redirect("details.aspx?hid=" + hotelid);
        }
    }

    protected void gvResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvResults.PageIndex = e.NewPageIndex;
        GoSearch();
    }

    protected void ddlSortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void rdoPricing_SelectedIndexChanged(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void chkrating_CheckedChange(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void chkAmenities_CheckChange(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("hotels-search.aspx");
    }

    protected void btnGo_Click(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        GoSearch();
    }

    protected void lnkbtnNextPage_Click(object sender, EventArgs e)
    {
        lnkbtnPreviousPage.Enabled = true;
        HotelSearchPaging("next");
    }

    protected void lnkbtnPreviousPage_Click(object sender, EventArgs e)
    {
        HotelSearchPaging("prev");
    }

    #region Travel Insurance

    protected void GetTravelInsurance()
    {
        Int64 countryid = 0;
        Int64 areaid = 0;
        string coveragelevel = "S";
        Int32 duration = 0;
        DateTime startdate = new DateTime(1900, 1, 1);
        DateTime enddate = new DateTime(1900, 1, 1);
        Int32 childage = 0;
        Int32 adultage1 = 0;
        Int32 adultage2 = 0;
        Int32 adultage3 = 0;
        Int32 adultage4 = 0;

        Int32 noofadults = 0;
        DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
        DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
        DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
        DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
        Int32 noofchilds = 0;
        DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
        DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
        DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
        DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
        DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
        DateTime dobchild6 = CE.Global.General.GetUTCDateTime();

        //Default Scenario


        string noofadult = inputTotalAdults.Value;
        string noofchild = inputTotalChild.Value;

        countryid = GetCountryIdOfExpediaCountry(inputCountryCode.Value);
        coveragelevel = "S";

        if (outbounddate != "" && inbounddate != "")
        {
            string[] outbounddateformatted = outbounddate.Split('/');
            string departuredate = outbounddateformatted[2] + "-" + outbounddateformatted[1] + "-" + outbounddateformatted[0];

            string[] inbounddateformatted = inbounddate.Split('/');
            string arrivaldate = inbounddateformatted[2] + "-" + inbounddateformatted[1] + "-" + inbounddateformatted[0];

            startdate = Convert.ToDateTime(arrivaldate);
            enddate = Convert.ToDateTime(departuredate);
        }
        else
        {
            startdate = CE.Global.General.GetUTCDateTime();
            enddate = CE.Global.General.GetUTCDateTime();
        }

        duration = ComputeDuration(startdate, enddate);
        adultage1 = 25; //default
        dobadult1 = CE.Global.General.GetUTCDateTime().AddYears(-25);//default
        noofadults = int.Parse(noofadult);
        noofchilds = int.Parse(noofchild);

        TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
        TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

        if (Session[General.TAId] == null)
        {
            _taapplicantsearch.TAAppSeaId = 0;
        }
        else
        {
            _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
        }

        if (Session[General.UserId] == null)
        {
            //_taapplicantsearch.RefCEUserId = CheckAndCreateAndSendMailToUser();
        }
        else
        {
            _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
        }

        _taapplicantsearch.Name = ""; // txtOwnerName.Text.Trim();
        _taapplicantsearch.EmailAddress = ""; // txtOwnerEmailAddress.Text.Trim();
        _taapplicantsearch.MobileNum = ""; // txtOwnerPhoneNo.GetPhoneNo().ToString();
        _taapplicantsearch.PlanType = "IND"; //Individual Default - ddlPolicyType.SelectedValue.ToString();
        _taapplicantsearch.TripType = "S"; //Single Default - ddlTripType.SelectedValue.ToString();
        _taapplicantsearch.CountryID = countryid;
        _taapplicantsearch.AreaID = areaid;
        _taapplicantsearch.CoverageLevel = coveragelevel;
        _taapplicantsearch.Duration = duration;
        _taapplicantsearch.StartDate = startdate;
        _taapplicantsearch.EndDate = enddate;
        _taapplicantsearch.ChildAge = childage;
        _taapplicantsearch.AdultAge = adultage1;
        _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
        _taapplicantsearch.TotalPremium = 0;

        _taapplicantsearch.NoofAdults = noofadults;
        _taapplicantsearch.DOBAdult1 = dobadult1;
        _taapplicantsearch.DOBAdult2 = dobadult2;
        _taapplicantsearch.DOBAdult3 = dobadult3;
        _taapplicantsearch.DOBAdult4 = dobadult4;
        _taapplicantsearch.NoofChilds = noofchilds;
        _taapplicantsearch.DOBChild1 = dobchild1;
        _taapplicantsearch.DOBChild2 = dobchild2;
        _taapplicantsearch.DOBChild3 = dobchild3;
        _taapplicantsearch.DOBChild4 = dobchild4;
        _taapplicantsearch.DOBChild5 = dobchild5;
        _taapplicantsearch.DOBChild6 = dobchild6;

        if (Session[General.ViewedDetailsId] == null || Session[General.ViewedDetailsId].ToString() == "")
        {
            //this.Page_Load(e, null);
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
        }

        _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

        _taapplicantsearch.Info1 = "0";
        Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

        if (_result > 0)
        {
            Session[General.TAId] = _result.ToString();

            if (Session[General.UserId] == null)
            {
                Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                Session[General.TAUserName] = ""; // txtFullName.Text;
                Session[General.TAPhoneNo] = ""; // txtMobileNo.GetPhoneNo().ToString();
                Session[General.TAEmail] = ""; // txtEmail.Text;
            }

            ResultsQuotesDataBind();
        }
    }

    protected void gvTAResultsInsurer_RowDatabound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[2].Text = String.Format("${0:f}", e.Row.Cells[2].Text);

            if (e.Row.Cells[2].Text == "0.01")
            {
                e.Row.Cells[2].Text = "";
                Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
                imgCompanyLogo.Visible = false;
            }
            else
            {
                Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
                string providercompanyid = DataBinder.Eval(e.Row.DataItem, "providercompanyid").ToString();
                string imageurl = "~/images/public/logo/";

                if (providercompanyid == "23")
                {
                    imageurl += "hsbc_xs.png";
                }
                else if (providercompanyid == "24")
                {
                    imageurl += "rsa_xs.png";
                }
                else if (providercompanyid == "29")
                {
                    imageurl += "liberty_xs.png";
                }
                else if (providercompanyid == "30")
                {
                    imageurl += "etiqa_xs.png";
                }
                else if (providercompanyid == "31")
                {
                    imageurl += "chartis_xs.png";
                }
                else if (providercompanyid == "34")
                {
                    imageurl += "chinataiping_xs.png";
                }
                else if (providercompanyid == "35")
                {
                    imageurl += "eq_xs.png";
                }
                else if (providercompanyid == "36")
                {
                    imageurl += "ace_xs.png";
                }
                else if (providercompanyid == "37")
                {
                    imageurl += "1cover_xs.png";
                }
                else if (providercompanyid == "38")
                {
                    imageurl += "directasia_xs.png";
                }

                imgCompanyLogo.ImageUrl = imageurl;
            }

            if (e.Row.RowIndex == 0)
                e.Row.CssClass = "packone tr";
            else if (e.Row.RowIndex == 1)
                e.Row.CssClass = "packtwo tr";
            else if (e.Row.RowIndex == 2)
                e.Row.CssClass = "packthree tr";
            else if (e.Row.RowIndex == 3)
                e.Row.CssClass = "packfour tr";
            else if (e.Row.RowIndex == 4)
                e.Row.CssClass = "packfive tr";
            else if (e.Row.RowIndex == 5)
                e.Row.CssClass = "packsix tr";
            else if (e.Row.RowIndex == 6)
                e.Row.CssClass = "packseven tr";
            else if (e.Row.RowIndex == 7)
                e.Row.CssClass = "packeight tr";


            ImageButton imgbtnCompare = new ImageButton();
            imgbtnCompare = (ImageButton)e.Row.FindControl("imgbtnCompare");

        }



    }

    protected void gvTAResultsInsurer_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Compare"))
        {
            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();

            string[] outbounddateformatted = inputCheckoutDate.Value.Split('/');
            string departuredate = outbounddateformatted[2] + "-" + outbounddateformatted[1] + "-" + outbounddateformatted[0];

            string[] inbounddateformatted = inputCheckinDate.Value.Split('/');
            string arrivaldate = inbounddateformatted[2] + "-" + inbounddateformatted[1] + "-" + inbounddateformatted[0];

            startdate = Convert.ToDateTime(arrivaldate);
            enddate = Convert.ToDateTime(departuredate);

            //removed popup
            //adultage1 = ComputeAge(userBirthday.GetDate());
            //dobadult1 = userBirthday.GetDate();

            adultage1 = 25; //default
            dobadult1 = CE.Global.General.GetUTCDateTime().AddYears(-25);//default

            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(startdate, enddate);

            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {
                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }
        }
    }

    private void ResultsQuotesDataBind()
    {
        if (Session[General.TAId] == null)
        {
            GetTravelInsurance();
        }

        GetTempResultTable();

    }

    private void GetTempResultTable()
    {
        string CoverType = "";
        Int32 Duration = 0;
        string CoverageLevel = "S";
        string Trip = "";
        Int64 AreaId = 0;
        Int64 CountryId = 0;
        Int32 AdultAge = 0;
        Int32 ChildAge = 0;
        Int64 TAId = 0;
        Int32 NoOfAdults = 0;

        TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();
        TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();

        if (Session[General.TAId] != null)
            TAId = Convert.ToInt64(Session[General.TAId]);
        else
        {
            GetTravelInsurance();
        }

        _taapplicantsearch = _taapplicantsearchdb.GetTAApplicantSearchItem(TAId);

        if (_taapplicantsearch != null)
        {
            CoverType = _taapplicantsearch.PlanType;
            Session["PlanType"] = _taapplicantsearch.PlanType;
            Duration = _taapplicantsearch.Duration;
            AreaId = _taapplicantsearch.AreaID;
            CountryId = _taapplicantsearch.CountryID;
            AdultAge = _taapplicantsearch.AdultAge;
            ChildAge = _taapplicantsearch.ChildAge;
            CoverageLevel = _taapplicantsearch.CoverageLevel;
            Trip = _taapplicantsearch.TripType;
            NoOfAdults = _taapplicantsearch.NoofAdults;

            incountryid.Value = CountryId.ToString();

            //Left label
            lblTrip.Text = GetTriptype(Trip);
            lblPolicyType.Text = GetCovertype(CoverType);
            lblNoOfTraveller.Text = NoOfAdults.ToString();

            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();

            TAQuoteResultDB _taquoteresultdb = new TAQuoteResultDB();


            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
            {
                _dtResult = _taquoteresultdb.GetTAQuoteResultDisplayByProvider(GetCovertype(CoverType), Duration.ToString(), AreaId, CountryId, AdultAge, ChildAge, CoverageLevel, Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()), NoOfAdults, 0, TAId);
            }
            else
            {
                _dtResult = _taquoteresultdb.GetTAQuoteResultDisplay(GetCovertype(CoverType), Duration.ToString(), AreaId, CountryId, AdultAge, ChildAge, CoverageLevel, Trip, NoOfAdults, 0, TAId);
            }


            DataView dv = new DataView(_dtResult);
            dv.Sort = "AnnualPremium ASC";

            Cache["TAResultsQuotes" + Session[General.TAId].ToString()] = dv.ToTable();

            string sQueryString = "";

            if (dv.Count > 0)
            {
                for (int i = 0; i < dv.ToTable().Rows.Count; i++)
                {
                    if (i == 7)
                    {
                        break;
                    }

                    string skey = dv.ToTable().Rows[i]["TAInsID"].ToString();
                    sQueryString += skey + ",";
                }


                Session["TASelected"] = sQueryString;
            }

            gvTAResultsInsurer.DataSource = GetTopDistinct(dv);
            gvTAResultsInsurer.DataBind();


        }
        else
        {
            Response.Redirect("~/travel-hotels/");
        }

    }

    private DataTable GetTopDistinct(DataView dv)
    {
        DataTable newdt = new DataTable();
        DataTable dt = dv.ToTable();

        string[] providers = new string[8]; //8 providers for now
        newdt = dt.Clone();

        int i = 0;
        foreach (DataRow row in dt.Rows)
        {
            if (i == 0)
            {
                providers[i] = row["ProviderCompanyId"].ToString();

                //newdt.ImportRow(row);
                newdt.Rows.Add(row.ItemArray);

            }
            else
            {
                bool isExisting = false;

                foreach (string prov in providers)
                {
                    if (row["ProviderCompanyId"].ToString() == prov)
                    {
                        isExisting = true;
                    }
                }

                if (!isExisting)
                {
                    if (newdt.Rows.Count < 8) // providers for now
                    {
                        int iprov = 0;
                        foreach (string prov in providers)
                        {
                            if (prov == null)
                            {
                                providers[iprov] = row["ProviderCompanyId"].ToString();

                                break;
                            }

                            iprov++;
                        }

                        newdt.Rows.Add(row.ItemArray);
                    }
                    else
                    {
                        break;
                    }

                }

            }
            i++;

            newdt.AcceptChanges();
        }
        return newdt;

    }

    private string GetCovertype(string covertype)
    {
        string coverparam = "";
        if (covertype == "IND")
            coverparam = "Individual";
        else if (covertype == "INS")
            coverparam = "IndividualSpouse";
        else if (covertype == "FML")
            coverparam = "Family";
        else if (covertype == "INC")
            coverparam = "IndividualChild";

        return coverparam;
    }

    private string GetTriptype(string trip)
    {
        string triptype = "";
        if (trip == "S")
            triptype = "Single Trip";
        else
            triptype = "Annual Multi-Trip";


        return triptype;
    }

    protected void btnSetReminder_Click(object sender, EventArgs e)
    {
        Page.Validate("reminder");
        ChangeValidationEffectServerSide("reminder");
        if (Page.IsValid)
        {
            UserSIRTravel _usersir = new UserSIRTravel();
            UserSIRTravelDB _usersirdb = new UserSIRTravelDB();
            _usersir = _usersirdb.GetSIRTravel(txtEmailAddress.Text.Trim(), "99999999");
            if (_usersir == null)
            {
                _usersir = new UserSIRTravel();
                _usersir.SIRTravelID = 0;
                _usersir.FullName = txtFullName.Text;
                _usersir.Email = txtEmailAddress.Text;
                _usersir.MobileNumber = "99999999";// txtMobileNo.GetPhoneNo();
                _usersir.ReminderMonth = Convert.ToInt16(ddlMonth.Text);
                _usersir.Status = true;

                _usersir.SIRTravelID = _usersirdb.Insert(_usersir);
                if (_usersir.SIRTravelID > 0)
                {
                    string _emailTo = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SIRMessageReceiver");
                    string _emailBody = "<br/><table><tr><td>Name</td><td>:</td><td>" + txtFullName.Text + "</td></tr>";
                    _emailBody += "<tr><td>Email</td><td>:</td><td>" + txtEmailAddress.Text + "</td></tr>";
                    // _emailBody += "<tr><td>Mobile</td><td>:</td><td>" + txtMobileNo.GetPhoneNo() + "</td></tr>";
                    _emailBody += "<tr><td>Reminder Month</td><td>:</td><td>" + ddlMonth.SelectedItem.Text + "</td></tr></table><br/><br/>Thank you.";

                    CE.Mail.MyMailManager.SendCRMMessage(_emailTo, "Travel Insurance Reminder (" + txtFullName.Text + ")", _emailBody);
                }
                else
                {
                    lblSetInsMessage.Text = "Transaction failed. Please try again later.";
                }
            }
            else
            {
                _usersir.FullName = txtFullName.Text;
                _usersir.ReminderMonth = Convert.ToInt16(ddlMonth.Text);
                _usersir.SIRTravelID = _usersirdb.Insert(_usersir);
            }

            if (_usersir != null && _usersir.SIRTravelID > 0)
            {
                lblSetInsMessage.Text = "Thank you for your request. We will send reminder to your email.";
                txtFullName.ReadOnly = true;
                txtEmailAddress.ReadOnly = true;
                //txtMobileNo.IsEnabled = false;
                ddlMonth.Enabled = false;
                btnSetReminder.Enabled = false;
                btnSetReminder.Visible = false;
            }
            else
            {
                lblSetInsMessage.Text = "Transaction failed. Please try again later.";
            }
        }
    }

    protected void btnUserInfo_Click(object sender, EventArgs e)
    {
        Page.Validate("userinfo");
        ChangeValidationEffectServerSideUserInfo("userinfo");
        if (Page.IsValid)
        {

            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();

            string[] outbounddateformatted = inputCheckoutDate.Value.Split('/');
            string departuredate = outbounddateformatted[2] + "-" + outbounddateformatted[1] + "-" + outbounddateformatted[0];

            string[] inbounddateformatted = inputCheckinDate.Value.Split('/');
            string arrivaldate = inbounddateformatted[2] + "-" + inbounddateformatted[1] + "-" + inbounddateformatted[0];

            startdate = Convert.ToDateTime(arrivaldate);
            enddate = Convert.ToDateTime(departuredate);


            adultage1 = ComputeAge(userBirthday.GetDate());
            dobadult1 = userBirthday.GetDate();
            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(startdate, enddate);


            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {
                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }

            LogUserViewedHistory();
        }
    }

    private int ComputeAge(DateTime dtBirth)
    {
        int Age = 0;

        DateTime now = CE.Global.General.GetUTCDateTime();// DateTime.Today;
        Age = now.Year - dtBirth.Year;
        // subtract another year if we're before the birthday in the current year
        if (now.Month < dtBirth.Month || (now.Month == dtBirth.Month && now.Day < dtBirth.Day))
            --Age;

        return Age;
    }

    private int ComputeDuration(DateTime dtFrom, DateTime dtTo)
    {
        int TripDuration = 0;
        TripDuration = Convert.ToInt32(dtTo.Subtract(dtFrom).TotalDays.ToString());
        TripDuration = TripDuration + 1;

        return TripDuration;
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Name
        if (rfvFullName.Enabled && rfvFullName.ValidationGroup == strValidationGroup)
        {
            rfvFullName.Validate();
            if (rfvFullName.IsValid == false)
            {
                txtFullName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFullName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        //Email Address
        if (rfvEmailAddress.Enabled && rfvEmailAddress.ValidationGroup == strValidationGroup)
        {
            rfvEmailAddress.Validate();
            if (rfvEmailAddress.IsValid == false)
            {
                txtEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtEmailAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }

        if (revEmailAddress.Enabled && revEmailAddress.ValidationGroup == strValidationGroup)
        {
            if (rfvEmailAddress.IsValid)
            {
                revEmailAddress.Validate();
                if (revEmailAddress.IsValid == false)
                {
                    txtEmailAddress.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtEmailAddress.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }
        //txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

        //Reminder Month
        if (rfvMonth.Enabled && rfvMonth.ValidationGroup == strValidationGroup)
        {
            rfvMonth.Validate();
            if (rfvMonth.IsValid == false)
            {
                ddlMonth.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlMonth.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlMonth.ControlStyle.CssClass = "";
        }


    }

    private void ChangeValidationEffectServerSideUserInfo(string strValidationGroup)
    {
        if (rfvUserName.Enabled && rfvUserName.ValidationGroup == strValidationGroup)
        {
            rfvUserName.Validate();
            if (rfvUserName.IsValid == false)
            {
                txtUserName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtUserName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "";
        }

        if (revUsername.Enabled && revUsername.ValidationGroup == strValidationGroup)
        {
            if (rfvUserName.IsValid)
            {
                revUsername.Validate();
                if (revUsername.IsValid == false)
                {
                    txtUserName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtUserName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "";
        }

        //Email Address
        if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
        {
            rfvUserEmail.Validate();
            if (rfvUserEmail.IsValid == false)
            {
                txtUserEmail.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtUserEmail.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "";
        }

        if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvUserEmail.IsValid)
            {
                revUserEmail.Validate();
                if (revUserEmail.IsValid == false)
                {
                    txtUserEmail.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtUserEmail.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "";
        }

        userBirthday.ChangeValidationEffectServerSide(strValidationGroup);
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("HO", Request, "Travel Hotels Results Page.");
    }

    private Int64 GetCountryIdOfExpediaCountry(string countrycode)
    {
        Int64 CountryId = 0;

        MyDatabase _db = new MyDatabase();
        DataTable _dtList = new DataTable("ExpCountryList");
        string _spName = "sprocExpediaCountryListSelectItemByCountryCode";
        SortedList _sPara = new SortedList();

        #region Parameter
        _sPara.Add("@CountryCode", countrycode);
        #endregion

        _dtList = _db.GetDataTableBySP(_spName, _sPara);


        if (_dtList.Rows.Count > 0)
        {
            CountryId = Int64.Parse(_dtList.Rows[0]["CXCountryId"].ToString());
        }


        return CountryId;
    }

    private string GetCountryNameOfExpediaCountry(string countrycode)
    {
        string countryname = "";

        MyDatabase _db = new MyDatabase();
        DataTable _dtList = new DataTable("ExpCountryList");
        string _spName = "sprocExpediaCountryListSelectItemByCountryCode";
        SortedList _sPara = new SortedList();

        #region Parameter
        _sPara.Add("@CountryCode", countrycode);
        #endregion

        _dtList = _db.GetDataTableBySP(_spName, _sPara);


        if (_dtList.Rows.Count > 0)
        {
            countryname = _dtList.Rows[0]["CountryName"].ToString();
        }


        return countryname;
    }

    protected void imgbtnRerun_Click(object sender, ImageClickEventArgs e)
    {
        //Response.Redirect("../travel-insurance/travel-quote.aspx");
        Response.Redirect("~/travel-insurance/");
    }

    #endregion

    #region Location

    static string SearchItem = "city";
    protected void ddlHotelNear_OnIndexChanged(object sender, EventArgs e)
    {
        SearchItem = ddlHotelNear.SelectedValue;
    }

    [System.Web.Services.WebMethod]
    public static string[] GetLocationSearch(string prefixText)
    {
        List<string> LocationNames = new List<string>();

        if (SearchItem != "city")
        {
            string _apikey = "98pndgasdzzxpugjzqpxw6za";
            int _minorrev = 13;
            Int64 _cid = 381988;

            HotelServicesImplService hws = new HotelServicesImplService();

            LocationInfoRequest locinforeq = new LocationInfoRequest();
            locinforeq.apiKey = _apikey;
            locinforeq.cid = _cid;
            locinforeq.minorRev = _minorrev;
            locinforeq.minorRevSpecified = true;
            locinforeq.customerIpAddress = "";// Request.UserHostAddress;
            locinforeq.customerUserAgent = ""; // Request.Browser.ToString();
            locinforeq.customerSessionId = "";

            if (SearchItem == "city")
            {
                locinforeq.type = LocationInfoType.Item1;
            }
            else
            {
                locinforeq.type = LocationInfoType.Item2;
            }

            locinforeq.destinationString = prefixText;
            locinforeq.locale = LocaleType.en_US;
            locinforeq.localeSpecified = true;
            locinforeq.ignoreSearchWeight = true;
            locinforeq.useGeocoder = false;
            locinforeq.typeSpecified = true;

            HotelWS.LocationInfoResponse locinforesp = new HotelWS.LocationInfoResponse();
            locinforesp = hws.getGeoLocation(locinforeq);
            string locitem = "";
            string locitemrow = "";

            if (locinforesp.EanWsError == null)
            {
                foreach (HotelWS.LocationInfo locinfo in locinforesp.LocationInfos.LocationInfo)
                {
                    if (locinforeq.type == LocationInfoType.Item2) //landmark
                    {
                        locitemrow = locinfo.description + ", " + locinfo.countryName + ", " + locinfo.countryCode;
                        locitem = AutoCompleteExtender.CreateAutoCompleteItem(locitemrow, locinfo.destinationId);

                        LocationNames.Add(locitem);
                    }
                    else
                    {
                        if (locinfo.stateProvinceCode != null && locinfo.stateProvinceCode != "")
                        {
                            locitemrow = locinfo.city + ", " + locinfo.stateProvinceCode + ", " + locinfo.countryName + ", " + locinfo.countryCode;
                            locitem = AutoCompleteExtender.CreateAutoCompleteItem(locitemrow, locinfo.destinationId);

                            LocationNames.Add(locitem);

                        }
                        else
                        {
                            locitemrow = locinfo.city + ", " + locinfo.countryName + ", " + locinfo.countryCode;
                            locitem = AutoCompleteExtender.CreateAutoCompleteItem(locitemrow, locinfo.destinationId);

                            LocationNames.Add(locitem);

                        }
                    }

                }
            }
            else
            {
                locitem = "no result. try other keywords";

                LocationNames.Add(locitem);
            }
        }
        else //CITY
        {
            string destid = "";
            string locitem = "";
            string locitemrow = "";

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CX_DBConnectionString"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("select top 9 DestinationId, Destination, Country, StateProvince, CountryCode from tblexpediadestinationdetail where CountryCode is not null and Destination like '" + prefixText + "%' ", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    destid = dt.Rows[i]["DestinationID"].ToString();

                    if (dt.Rows[i]["StateProvince"].ToString() != "")
                        locitemrow = dt.Rows[i]["Destination"].ToString() + ", " + dt.Rows[i]["StateProvince"].ToString() + ", " + dt.Rows[i]["Country"].ToString() + ", " + dt.Rows[i]["CountryCode"].ToString();
                    else
                        locitemrow = dt.Rows[i]["Destination"].ToString() + ", " + dt.Rows[i]["Country"].ToString() + ", " + dt.Rows[i]["CountryCode"].ToString();

                    locitem = AutoCompleteExtender.CreateAutoCompleteItem(locitemrow, destid);

                    LocationNames.Add(locitem);
                }
            }
            else
            {
                locitem = "no result. try other keywords";

                LocationNames.Add(locitem);
            }

        }
        return LocationNames.ToArray();
    }

    #endregion


    private string getXMLResult(string requestData)
    {
        WebRequest request = null;
        request = WebRequest.Create(requestData);
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        responseFromServer = responseFromServer.Replace("@", "");
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }
}
